package au.com.mason.propertyTracker.util;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;

import au.com.mason.propertyTracker.domain.Property;

public class HttpClientWrapper {

	private HttpClient client;
	private HttpMethod method;
	
	public void init(String url) {
		client = new HttpClient();
		method = new GetMethod(url);
	}
	
	public void initAndExecute(String url) {
		init(url);
		
		try {
			int status = client.executeMethod(method);
			if (status == HttpStatus.SC_MOVED_PERMANENTLY) {
				method.recycle();
				method = new GetMethod(url);
				status = client.executeMethod(method);
			}
			
		} 
		catch (Exception e) {
			System.out.println(e.getMessage());
		}
	}
	
	public boolean isRemoved(Property property) {
		try {
			int status = client.executeMethod(method);
			if (status == HttpStatus.SC_MOVED_PERMANENTLY) {
				method.recycle();
				method = new GetMethod(property.getUrl());
				status = client.executeMethod(method);
				System.out.println("status - " + status + " for " + property.getUrl());
			}
			if (status == HttpStatus.SC_MOVED_PERMANENTLY) {
				return true;
			}
		}
		catch (Exception e) {
			System.out.println(e.getMessage());
		}

		
		return false;
	}
	
	public String getResponse() {
		return method.getResponseBodyAsString();
	}
}
